const express = require('express');
const router = express.Router();
const Admin = require("../sql/collection/Admin");
const sql = require("../sql/index");
const md5 = require("md5");

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    activeIndex: "0",
    role: req.session.role,
    adminname: req.session.adminname
  });
});
router.get('/login', function (req, res, next) {
  res.render('login');
});
router.post('/loginAction', function (req, res, next) {
  let { adminname, password } = req.body;
  // 存储的密码是进行加密过的
  password = md5(password);
  // 获取表单信息，进行效验
  sql.find(Admin, { adminname, password }, { _id: 0 }).then((data) => {
    if (data.length === 0) {
      res.redirect("/login");
    } else {
      // res.cookie("loginStart", true);
      // res.cookie("role", data[0].role);
      req.session.loginStart = true;
      req.session.adminname = data[0].adminname;
      req.session.role = data[0].role;
      res.redirect("/");
    }
  })
});
module.exports = router;
